package com.itheima.stock.service.imp;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.itheima.stock.entity.StockBlockRtInfo;
import com.itheima.stock.entity.StockBusiness;
import com.itheima.stock.entity.StockMarketIndexInfo;
import com.itheima.stock.entity.StockRtInfo;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.properties.MarketProperties;
import com.itheima.stock.service.StockTimerService;
import com.itheima.stock.util.IdWorkers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 李智勇
 * @data 2025/11/16 21:12
 */
@Service

public class StockTimerServiceImpl implements StockTimerService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private IdWorkers idWorkers;
@Autowired
private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
@Autowired
private MarketProperties marketProperties;
@Autowired
private StockBusinessMapper stockBusinessMapper;
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;

    @Override
    public void getStockBlockInfo() {
        String url = "http://vip.stock.finance.sina.com.cn/q/view/newSinaHy.php";
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","https://finance.sina.com.cn");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36");
        HttpEntity<?> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        String body = response.getBody();
        String regex = "var S_Finance_bankuai_sinaindustry = (.+)";
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(body);
        List<StockBlockRtInfo> stockBlockRtInfos = Lists.newArrayList();
        while (matcher.find()){
            String jsonStr = matcher.group(1);
            Map map = JSON.parseObject(jsonStr, Map.class);

            System.out.println( map);
            Collection values = map.values();
            for (Object valueStr : values){
                String value = valueStr.toString();
                String[] resArr = value.split(",");
                String label = resArr[0];
                String bkock_name = resArr[1];
                String company_num_str = resArr[2];
                Integer company_num = Integer.parseInt(company_num_str);
                String avg_price_str = resArr[3];
                BigDecimal avg_price = new BigDecimal(avg_price_str);
                String updown_rate_str = resArr[5];
                BigDecimal updown_rate = new BigDecimal(updown_rate_str);
                String trade_amount_str = resArr[6];
                Long trade_amount = Long.parseLong(trade_amount_str);
                String trade_volume_str = resArr[7];
                BigDecimal trade_volume = new BigDecimal(trade_volume_str);
                StockBlockRtInfo blockRtInfo = StockBlockRtInfo.builder()
                        .id(idWorkers.nextStrId())
                        .label(label)
                        .blockName(bkock_name)
                        .avgPrice(avg_price)
                        .updownRate(updown_rate)
                        .tradeAmount(trade_amount)
                        .tradeVolume(trade_volume)
                        .companyNum(company_num)
                        .curTime(LocalDateTime.now())
                        .build();
                stockBlockRtInfos.add( blockRtInfo);

            }

        }

        Lists.partition(stockBlockRtInfos, 10).stream().forEach(list -> {
            stockBlockRtInfoMapper.insertBach(list);
        });
    }

    @Override
    public void getStockInfo(String bizId) {
        String urlPrefix = "https://hq.sinajs.cn/list";
        List<StockBusiness> stockBusinesses = stockBusinessMapper.selectAll();
        List<String> sec_code_List = stockBusinesses.stream().map(business -> {
            if (business.getSecCode().startsWith("00")) {
                return String.join("","sz", business.getSecCode());
            } else if (business.getSecCode().startsWith("60")) {
                return String.join("","sh", business.getSecCode());
            } else {
                return null;
            }
        }).toList();
        String param = String.join(",", sec_code_List);
        String url = String.join("=", urlPrefix, param);
        HttpMethod method = HttpMethod.GET;
        HttpHeaders header = new HttpHeaders();
        header.add("Referer","http://finance.sina.com.cn");
        header.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36");
        HttpEntity<?> entity = new HttpEntity<>(header);
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        String body = response.getBody();
        String regex = "var hq_str_(.+)=\"(.+)\";";
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(body);
        List<StockRtInfo> stockRtInfoList = Lists.newArrayList();
        while (matcher.find()) {
            String stcok_code = matcher.group(1).substring(2);
            String resStr = matcher.group(2);
            String[] resArr = resStr.split(",");
            String stcok_name = resArr[0];
            String open_price_str = resArr[1];
            BigDecimal open_price = new BigDecimal(open_price_str);
            String pre_close_price_str = resArr[2];
            BigDecimal pre_close_price = new BigDecimal(pre_close_price_str);
            String cur_price_str = resArr[3];
            BigDecimal cur_price = new BigDecimal(cur_price_str);
            String max_price_str = resArr[4];
            BigDecimal max_price = new BigDecimal(max_price_str);
            String min_price_str = resArr[5];
            BigDecimal min_price = new BigDecimal(min_price_str);
            String trade_amount_str = resArr[8];
            Long trade_amount = Long.parseLong(trade_amount_str);
            String trade_volume_str = resArr[9];
            BigDecimal trade_volume = new BigDecimal(trade_volume_str);
            String date_str = resArr[30];
            String time_str = resArr[31];
            String date_time_str = String.join(" ", date_str, time_str);
            LocalDateTime curTime = LocalDateTime.parse(date_time_str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            StockRtInfo stockRtInfo = StockRtInfo.builder()
                    .id(idWorkers.nextId())
                    .stockCode(stcok_code)
                    .stockName(stcok_name)
                    .openPrice(open_price)
                    .preClosePrice(pre_close_price)
                    .curPrice(cur_price)
                    .maxPrice(max_price)
                    .minPrice(min_price)
                    .tradeAmount(trade_amount)
                    .tradeVolume(trade_volume)
                    .curTime(curTime)
                    .build();
            stockRtInfoList.add(stockRtInfo);
        }
        Lists.partition(stockRtInfoList, 10).stream().forEach(list -> {
            stockRtInfoMapper.insertBach(list);
        });
    }

    @Override
    public void getInnerMarketInfo() {
        String urlPrefix = "http://hq.sinajs.cn/list=";
        List<String> ids = marketProperties.getInner();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < ids.size(); i++) {
            if (i != ids.size() - 1) {
                stringBuilder.append(ids.get(i)).append(",");
            } else {
                stringBuilder.append(ids.get(i));
            }
        }
        String url = String.join("=", urlPrefix, stringBuilder.toString());
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","http://finance.sina.com.cn");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36");
        HttpEntity<?> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);
        String body = response.getBody();
        String regex = "var hq_str_(.+)=\"(.+)\";";
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(body);
        List<StockMarketIndexInfo> stockMarketIndexInfoList = Lists.newArrayList() ;
        while (matcher.find()){
            String mark_id = matcher.group(1);
            String resStr = matcher.group(2);
            String[] resArr = resStr.split(",");
            String market_name = resArr[0];
            String cur_point_str = resArr[1];
            BigDecimal cur_point = BigDecimal.valueOf(Double.parseDouble(cur_point_str));
            String currrent_price_str = resArr[2];
            BigDecimal currrent_price = BigDecimal.valueOf(Double.parseDouble(currrent_price_str));
            String updown_rate_str = resArr[3];
            BigDecimal updown_rate = BigDecimal.valueOf(Double.parseDouble(updown_rate_str));
            String trade_amount_str = resArr[4];
            Long trade_amount = Long.parseLong(trade_amount_str);
            String trade_volume_str = resArr[5];
            Long trade_volume = Long.parseLong(trade_volume_str);
            StockMarketIndexInfo stockMarketIndexInfo = StockMarketIndexInfo.builder()
                    .id(idWorkers.nextStrId())
                    .markId(mark_id)
                    .markName(market_name)
                    .currentPrice(currrent_price)
                    .curPoint(cur_point)
                    .tradeAccount(trade_amount)
                    .tradeVolume(trade_volume)
                    .updownRate(updown_rate)
                    .curTime(LocalDateTime.now())
                    .build();
            stockMarketIndexInfoList.add(stockMarketIndexInfo);
        }
        stockMarketIndexInfoMapper.insertBatch(stockMarketIndexInfoList);
    }
}
